package com.example.mingyue.controller;


import com.example.mingyue.Exception.searchTypeisNullException;
import com.example.mingyue.common.PageBean;
import com.example.mingyue.common.Result;
import com.example.mingyue.constant.MessageConstant;
import com.example.mingyue.datasource.DataSource;
import com.example.mingyue.datasource.PictureDataSource;
import com.example.mingyue.datasource.PostDataSource;
import com.example.mingyue.datasource.UserDataSource;
import com.example.mingyue.model.dto.SearchDto;
import com.example.mingyue.model.entity.Picture;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.model.enums.SearchEnum;
import com.example.mingyue.model.vo.PostVO;
import com.example.mingyue.model.vo.SearchVO;
import com.example.mingyue.model.vo.UserVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 搜索门面
 */
@RestController
@RequestMapping("/search")
@Slf4j
public class SearchController {

    @Resource
    private PictureDataSource pictureDataSource;
    @Resource
    private PostDataSource pictureData;
    @Resource
    private UserDataSource userDataSource;
//    @Resource
//    private DataSource dataSource;

    @PostMapping("/all")
    public Result search(@RequestBody SearchDto searchDto){

        String type = searchDto.getType();
        //如果搜索类型不是枚举中的任何一个，抛出
        if(type == null){
            throw new searchTypeisNullException(MessageConstant.SEARCH_TYPE_ISNULL);
        }
        //查看是哪一个类型
        SearchEnum searchType = SearchEnum.getEnumByValue(type);
        System.out.println("查看"+searchType);
        String searchText = searchDto.getSearchText();
        Integer page = searchDto.getPage();
        Integer pageSize = searchDto.getPageSize();

        if(searchType == null){

            PageBean<UserVO> userPageBean = userDataSource.doSearch(searchText,page,pageSize);
            PageBean<Post> postPageBean = pictureData.doSearch(searchText,page,pageSize);
            PageBean<Picture> pictureData = pictureDataSource.doSearch(searchText,page,pageSize);

            SearchVO searchVO = new SearchVO();
            searchVO.setUserList(userPageBean);
            searchVO.setPostList(postPageBean);
            searchVO.setPictureList(pictureData);
            return Result.success(searchVO);
        }else{
            DataSource dataSource = null;
            switch (searchType){
                case USER -> dataSource = userDataSource;
                case POST -> dataSource = pictureData;
                case Picture -> dataSource = pictureDataSource;
            }

            PageBean result = dataSource.doSearch(searchText,page,pageSize);

            return Result.success(result);

        }


    }




}
